package com.example.JPetStore;

import com.alibaba.fastjson.JSONObject;
import com.example.JPetStore.dao.UserDao;
import com.example.JPetStore.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.*;

@Component
public class Common {

    static UserDao userDao;


    public static void sendErrorMessage(ModelAndView mv, String message, String url){
        System.out.println("message:"+message);
        try {
            message= URLEncoder.encode(message,"utf-8");
            String page = "/common/message.html?message="+message+"&url="+url;
            mv.setViewName("redirect:"+page);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String Success(JSONObject data){
        JSONObject result=new JSONObject();
        result.put("data",data);
        result.put("status",200);
        return result.toJSONString();
    }
    public static String Fail(String msg){
        JSONObject result=new JSONObject();
        result.put("msg",msg);
        result.put("status",500);
        return result.toJSONString();
    }
    public static User checkLogin(ModelAndView mv, HttpSession session){
        User user;

        //调试使用，跳过登陆
//        user= userDao.queryUser("101");
//        session.setAttribute("user",user);

        user=(User) session.getAttribute("user");
        if(user==null){
            Common.sendErrorMessage(mv,"未登录！","/account/login.html");
            return user;
        }
        //更新登陆时间
        userDao.updateLoginTimestamp(user);
        return user;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
        Common.userDao = userDao;
    }

    public static String md5(String str){
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }
}